package com.gitee.ixtf.vertx.handler

import io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE
import io.netty.handler.codec.http.HttpHeaderValues.APPLICATION_JSON
import io.vertx.core.Handler
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.core.json.jsonObjectOf
import jakarta.inject.Singleton

@Singleton
class FailureHandler : Handler<RoutingContext> {
  override fun handle(rc: RoutingContext) {
    rc.response()
        .takeUnless { it.ended() }
        ?.apply {
          try {
            statusCode = rc.statusCode()
            when (statusCode) {
              in 401 until 500 -> end()
              else -> {
                putHeader(CONTENT_TYPE, APPLICATION_JSON)
                end(jsonObjectOf("errMsg" to rc.failure().message).encode())
              }
            }
          } catch (t: Throwable) {
            statusCode = 500
            end(t.message)
          }
        }
  }
}
